using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Reflection;
using System.Data.Common;

namespace AAM.SQL
{
    public class ConnectionManager : Dictionary<string, Connection>
    {

        public static readonly ConnectionManager Instance = new ConnectionManager();

        public Connection OpenConnection(string connectionName)
        {
            try
            {
                Connection connection = base[connectionName];
                //if (connection.DbConnection.State == System.Data.ConnectionState.Closed) connection.DbConnection.Open();
                return connection;
            }
            catch (KeyNotFoundException)
            {
                string connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
                string connectionType = ConfigurationManager.AppSettings["connectionType"];
                Type type = Type.GetType(connectionType);
                ConstructorInfo info = type.GetConstructor(new Type[] { typeof(string) });
                Connection connection = new Connection((DbConnection)info.Invoke(new object[] { connectionString }));
                connection.DbConnection.Open();
                base.Add(connectionName, connection);
                return connection;
            }
        }

        public void CloseConnection(string connectionName)
        {
            if (base.ContainsKey(connectionName))
            {
                base[connectionName].DbConnection.Close();
                base.Remove(connectionName);
            }
        }

    }
}
